package com.chenhao.generator.util;

import com.chenhao.generator.entity.GeneratorParam;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.File;
import java.io.FileWriter;

/**
 * 模板代码生成器
 *
 * @author:chenHao
 * @version:1.0
 * @since:1.0
 * @createTime:2019-10-02
 */
public abstract class Creator {

    public static void create(GeneratorParam params, String srcPath, String templateFilePath) throws Exception {
        FileWriter writer = null;
        try {
            // 获取所有模板文件
            String[] resources = FileUtil.getResources(Creator.class, templateFilePath);
            Configuration cfg = new Configuration();
            cfg.setDefaultEncoding("UTF-8");
            cfg.setClassForTemplateLoading(Creator.class, "/");
            for (String resource : resources) {
                //生成后的模板名称
                Template template = cfg.getTemplate(resource);
                String templateClassNameName = resource.replace(templateFilePath, "");
                String className = StringUtil.processTemplate(templateClassNameName, params);
                File templateFile = new File(srcPath + className);
                File parentFile = templateFile.getParentFile();
                //创建文件夹
                if (!parentFile.exists()) {
                    parentFile.mkdirs();
                }
                writer = new FileWriter(templateFile);
                template.process(params, writer);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if (writer != null) {
                writer.flush();
                writer.close();
            }
        }
    }


}
